package cn.com.rocketmq.order;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 顺序消息消费者
 */
public class Consumer {

    /**
     * 日志对象
     */
    private static  final Logger logger = LoggerFactory.getLogger(Consumer.class);

    public static void main(String[] args) {
        try {
            DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group_rocketmq_orderDemo");
            consumer.setNamesrvAddr("192.168.113.101:9876");
            consumer.subscribe("rocketmq_orderDemo", "*");
            //MessageListenerOrderly有序消息监听
            consumer.setMessageListener(new MessageListenerOrderly() {
                @Override
                public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
                    list.forEach(item -> {
                        try {
                            logger.info("消息接收成功！消息队列={}，消息ID={},消息内容={}", item.getQueueId(), item.getMsgId(), new String(item.getBody(), "UTF-8"));
                        } catch (Exception e) {
                            logger.error("消息接收异常！", e);
                        }
                    });
                    return ConsumeOrderlyStatus.SUCCESS;
                }
            });
            consumer.start();
        } catch (Exception e) {
            logger.error("消息接收异常！", e);
        }
    }
}
